package org.gry.dy20180614;

import java.sql.*;
import java.sql.SQLException;

public class DatabaseTest {
	// JDBC 驱动名及数据库 URL
	static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	static final String DB_URL = "jdbc:mysql://localhost:3306/candy";
	// 数据库的用户名与密码，需要根据自己的设置
	static final String USER = "root";
	static final String PASS = "1356";

	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");// 注册 JDBC 驱动
			System.out.println("连接数据库...");// 打开链接
			conn = DriverManager.getConnection(DB_URL, USER, PASS);
			System.out.println(" 实例化Statement对象...");// 执行查询
			stmt = conn.createStatement();
			String sql;
			sql = "SELECT * FROM candy";
			ResultSet rs = stmt.executeQuery(sql);

			while (rs.next()) {// 展开结果集数据库
				int id = rs.getInt("candy_id");// 通过字段检索
				String name = rs.getString("candy_name");
				String price = rs.getString("candy_price");
				System.out.print("ID: " + id);// 输出数据
				System.out.print(", 糖果名称: " + name);
				System.out.print(", 糖果价钱: " + price);
				System.out.print("\n");
			}
			// 完成后关闭
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException se) {
			se.printStackTrace();// 处理 JDBC 错误
		} catch (Exception e) {
			e.printStackTrace();// 处理 Class.forName 错误
		} finally {

			try {// 关闭资源
				if (stmt != null)
					stmt.close();
			} catch (SQLException se2) { // 什么都不做
			}
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException se) {
				se.printStackTrace();
			}
		}
		System.out.println("Goodbye!");
	}
}
